﻿using Commons;
using Core;
using Core.Factory;
using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using WebApp.Models;

namespace WebApp.Serivces
{
    public class FireServices : IFireServices
    {
        private readonly IBaseService _baseService;
        private readonly IActivityService _activityService;
        private readonly IJoinService _joinService;
        private readonly string appid = MyConfigurationSection.GetSite("AppID");
        private readonly string secret = MyConfigurationSection.GetSite("Secret");
        private readonly string _template_id = MyConfigurationSection.GetSite("WeappTemplate");
        private readonly string _page = MyConfigurationSection.GetSite("ToPage");
        private readonly string _messageUrl = MyConfigurationSection.GetSite("MessageUrl");
        /// <summary>
        /// 发送构造函数
        /// </summary>
        /// <param name="baseService"></param>
        /// <param name="activityService"></param>
        /// <param name="joinService"></param>
        public FireServices(IBaseService baseService, IActivityService activityService, IJoinService joinService)
        {
            _baseService = baseService;
            _activityService = activityService;
            _joinService = joinService;
        }
        /// <summary>
        /// 发送模板消息
        /// </summary>
        /// <param name="activityId"></param>
        public void OpenActivity(int activityId)
        {
            DateTime time = DateTime.Now;

            var joins = _baseService.GetList<T_Join>(i => i.ActivityId == activityId);
            var activity = _baseService.GetModel<T_Activity>(i => i.Id == activityId);
            var details = _baseService.GetList<T_ActivityDetail>(i => i.ActivityId == activityId);

            Random random = new Random();

            if (activity == null)
            {
                return;
            }
            else if (activity.IsOpen != 0)
            {
                return;
            }
            if (activity.OpenCount != null)
            {
                if (activity.OpenCount.Value > 0 && activity.OpenCount > joins.Count)
                {
                    //人数不够，未开奖
                    var dataA = new { keyword1 = new { value = "活动指南" }, keyword2 = new { value = activity.Title }, keyword3 = new { value = time.ToString("yyyy-MM-dd HH:mm:ss") }, keyword4 = new { value = "您发起的活动未开奖，因参与人数不够，点击查看详情" } };
                    SendMsg(_baseService.GetModel<T_User>(u => u.Id == activity.UserId).WxOpenId, dataA, activity.Id, activity.UserId, "Publish");
                    _activityService.UpdateOpen(activity.Id, 2);

                    return;
                }
            }
            if (details == null || details.Count == 0)
            {
                //未找到活动信息
                var dataA = new { keyword1 = new { value = "活动指南" }, keyword2 = new { value = activity.Title }, keyword3 = new { value = time.ToString("yyyy-MM-dd HH:mm:ss") }, keyword4 = new { value = "未找到您发起的活动" } };
                SendMsg(_baseService.GetModel<T_User>(u => u.Id == activity.UserId).WxOpenId, dataA, activity.Id, activity.UserId, "Publish");
                _activityService.UpdateOpen(activity.Id, 2);

                return;
            }
            if (joins == null || joins.Count == 0)
            {
                //无人参加活动

                //为发起者发送开奖通知
                var dataB = new { keyword1 = new { value = "活动指南" }, keyword2 = new { value = activity.Title }, keyword3 = new { value = time.ToString("yyyy-MM-dd HH:mm:ss") }, keyword4 = new { value = "您发起的活动未开奖，因参与人数为0，点击查看详情" } };
                SendMsg(_baseService.GetModel<T_User>(u => u.Id == activity.UserId).WxOpenId, dataB, activity.Id, activity.UserId, "Publish");
                _activityService.UpdateOpen(activity.Id, 2);

                return;
            }
            List<int> lucks = new List<int>();
            List<T_Join> joinLucks = new List<T_Join>();
            foreach (var item in details)
            {
                var number = item.Number;
                for (int i = 0; i < Convert.ToInt32(number); i++)
                {
                    int index = GetRandom(lucks, joins.Count);
                    lucks.Add(index);
                    T_Join join = joins[index];
                    join.IsLucky = 1;
                    join.ActivityDetailId = item.Id;
                    joinLucks.Add(join);

                }
            }
            foreach (var item in joins)
            {
                string openid = _baseService.GetModel<T_User>(u => u.Id == item.UserId).WxOpenId;
                var data = new { keyword1 = new { value = "活动指南" }, keyword2 = new { value = activity.Title }, keyword3 = new { value = time.ToString("yyyy-MM-dd HH:mm:ss") }, keyword4 = new { value = "您参加的活动已开奖，请查看" } };
                SendMsg(openid, data, activity.Id, item.UserId,"Join");
            }
            //为发起者发送开奖通知
            var data2 = new { keyword1 = new { value = "活动指南" }, keyword2 = new { value = activity.Title }, keyword3 = new { value = time.ToString("yyyy-MM-dd HH:mm:ss") }, keyword4 = new { value = "您发起的活动已开奖，请查看" } };
            SendMsg(_baseService.GetModel<T_User>(u => u.Id == activity.UserId).WxOpenId, data2, activity.Id, activity.UserId,"Publish");
            _activityService.UpdateOpen(activity.Id, 1);

            _joinService.UpdateJoins(joinLucks);
        }
        /// <summary>
        /// GetRandom
        /// </summary>
        /// <param name="indexs"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        private int GetRandom(List<int> indexs, int end)
        {
            Random random = new Random();

            int index = random.Next(0, end);
            if (indexs.Contains(index))
            {
                index = GetRandom(indexs, end);
            }
            return index;
        }
        /// <summary>
        /// 为小程序推送消息
        /// </summary>
        private void SendMsg(string touser, object data, int activityId, int userId,string flag)
        {

            string accessToken = GetAccessToken();

            HttpClient client = new HttpClient();

            var formid = _activityService.GetFormId(userId,flag);
            TemplateMessage templateMessage = new TemplateMessage();
            templateMessage.touser = touser;
            templateMessage.access_token = accessToken;
            templateMessage.form_id = formid;
            templateMessage.page = _page + activityId;
            templateMessage.template_id = _template_id;
            templateMessage.emphasis_keyword = "";
            templateMessage.data = data;

            HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(templateMessage));
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            HttpResponseMessage response = client.PostAsync(_messageUrl + accessToken, httpContent).Result;
            string result = response.Content.ReadAsStringAsync().Result;
            client.Dispose();
            TemplateResult access = JsonConvert.DeserializeObject<TemplateResult>(result);
            if (access.errcode != 0)
            {
                _activityService.UpdateForm(formid);
            }
        }
        /// <summary>
        /// 微信接口凭证
        /// </summary>
        /// <returns></returns>
        private string GetAccessToken()
        {
            HttpClient client = new HttpClient();
            HttpResponseMessage response = client.GetAsync("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret).Result;
            string result = response.Content.ReadAsStringAsync().Result;
            client.Dispose();
            AccessModel access = Newtonsoft.Json.JsonConvert.DeserializeObject<AccessModel>(result);
            if (access != null && access.errcode == 0)
            {
                return access.access_token;
            }
            return "";
        }
    }
}
